<?php



namespace Yi\Wechat\Services;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
// use Yi\Wechat\Services\AccessToken;


class Wechat
{

    public static $appId;
    public static $appSecret;
    public static $accessTokenCacheKey;

    private static $instance = null;

    private function __construct($config)
    {
        // 私有构造函数
        self::$appId = $config['app_id'];
        self::$appSecret = $config['secret'];
        self::$accessTokenCacheKey = "wechat_access_token_" . $config['app_id'];
    }


    public static function init(array $config)
    {
        if (self::$instance === null) {
            self::$instance = new self($config);
        }
        return self::$instance;
    }

    /** 
     * 生成AccessToken
     */
    private  static function AccessToken()
    {
        $accessToken = Redis::get(self::$accessTokenCacheKey);
        if (!$accessToken) {
            $getTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?';
            $reqUrl = $getTokenUrl . http_build_query([
                'grant_type' => 'client_credential',
                'appid' => self::$appId,
                'secret' => self::$appSecret
            ]);
            Log::debug("AccessToken_request_url:", [
                'grant_type' => 'client_credential',
                'appid' => self::$appId,
                'secret' => self::$appSecret
            ]);
            $request = new Request('get', $reqUrl);

            $client = new Client();
            $response = $client->send($request, ['http_errors' => false]);
            $content = $response->getBody()->getContents();;
            $result = json_decode($content, true, 512, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
            if (isset($result['errcode'])) {
                Log::debug($content);
                // throw new WechatRuntimeException('获取AccessToken失败');
                return $result;
            }
            $accessToken = $result['access_token'];
            Redis::setex(self::$accessTokenCacheKey, 7000, $accessToken);
        }
        // return ['accessToken' => $accessToken];
        return $accessToken;
    }

    public static function getAccessToken()
    {
        return self::AccessToken();
    }

    // public static function hello()
    // {
    //     self::init();
    //     echo self::$Client;
    //     echo "<hr>";
    //     echo "Hello, I'm the static object!";
    // }
    function sendSubsribeMsg()
    {
        $templateId = "bZbFBXcbmOAwOZo4ii6GimmjQtokwrTA9vkQM2E0bW8";
        $openid = "oew6R6yRzG52n1O9TK50WVc9Nha4";
        $message = self::getMsg($openid, $templateId);
        $res = self::send($templateId, $openid, $message);
        var_dump($res);
        return $res;
    }

    public static function getMsg($openid, $template_id)
    {
        $data['data'] = [
            'thing1' => ['value' => '活动名称', 'color' => ''],
            'time2' => ['value' => date("Y-m-d H:i:s"), 'color' => ''],
            'thing4' => ['value' => '活动地点', 'color' => '']
        ]; //内容主体
        $data['touser'] = $openid; //用户的openid
        $data['template_id'] = $template_id; //从微信后台获取的模板id
        Log::debug("wechat_getMsg_mk_data", $data);
        return $data;
    }


    public static function send($template_id, $openid, $message)
    {
        $access_token = self::getAccessToken();
        $send_url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;

        Log::info("wechat_send_url:" . $send_url);


        Log::debug("wechat_send_message", $message);
        $str = self::curl_post($send_url, json_encode($message));
        $str = json_decode($str, 1);
        return $str;
    }
    public static function curl_post($url, $fields, $data_type = 'text')
    {
        $cl = curl_init();
        if (stripos($url, 'https://') !== FALSE) {
            curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($cl, CURLOPT_SSLVERSION, 1);
        }
        curl_setopt($cl, CURLOPT_URL, $url);
        curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($cl, CURLOPT_POST, true);
        curl_setopt($cl, CURLOPT_POSTFIELDS, $fields);
        $content = curl_exec($cl);
        $status = curl_getinfo($cl);
        curl_close($cl);
        if (isset($status['http_code']) && $status['http_code'] == 200) {
            if ($data_type == 'json') {
                $content = json_decode($content);
            }
            return $content;
        } else {
            return FALSE;
        }
    }
    public static function curl_get($url, $data_type = 'text')
    {
        $cl = curl_init();
        if (stripos($url, 'https://') !== FALSE) {
            curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($cl, CURLOPT_SSLVERSION, 1);
        }
        curl_setopt($cl, CURLOPT_URL, $url);
        curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
        $content = curl_exec($cl);
        $status = curl_getinfo($cl);
        curl_close($cl);
        if (isset($status['http_code']) && $status['http_code'] == 200) {
            if ($data_type == 'json') {
                $content = json_decode($content);
            }
            return $content;
        } else {
            return FALSE;
        }
    }
}
